package com.think.cloud.thinkshop.mall.rabbit.producer;

import cn.hutool.json.JSONUtil;
import com.think.cloud.thinkshop.common.enums.RabbitMessageTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

import static com.think.cloud.thinkshop.mall.rabbit.config.RabbitConfig.*;

@Component
@Slf4j
public class MessageProducer {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送普通消息
     *
     * @param message
     * @param type
     */
    public void sendMessage(String message, RabbitMessageTypeEnum type) {
        MessageProperties properties = new MessageProperties();
        properties.setType(type.getCode());
        Message msg = MessageBuilder.withBody(JSONUtil.toJsonStr(message).getBytes()).andProperties(properties).build();
        rabbitTemplate.convertAndSend(EXCHANGE_NAME, ROUTING_KEY_NAME, msg);
        log.info("+++++++++++++++++ 发送消息：类型：{},内容：{} +++++++++++++", type.getCode(),message);
    }

    /**
     * 发送延迟消息
     *
     * @param message 消息
     * @param delay   延时时间
     */
    public void sendDelayedMessage(String message, RabbitMessageTypeEnum type, long delay, TimeUnit unit) {
        MessageProperties properties = new MessageProperties();
        properties.setDelay(Math.toIntExact(unit.toMillis(delay))); // 延迟时间，单位为毫秒
        properties.setType(type.getCode());
        Message msg = MessageBuilder.withBody(message.getBytes()).andProperties(properties).build();
        rabbitTemplate.convertAndSend(DELAY_EXCHANGE_NAME, DELAY_ROUTING_KEY_NAME, msg);
        log.info("发送延迟消息：{}", message);
    }
}
